package com.du.web.sample.controller;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Desc :
 * @Author: shuangdu
 * @date : 2022/9/2
 */
@RestController
@RequestMapping(path = "redis")
@Slf4j
public class RedisController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("test")
    public void test() {
        redisTemplate.executePipelined(new SessionCallback<String>() {
            @Override
            public <K, V> String execute(RedisOperations<K, V> operations) throws DataAccessException {
                ZSetOperations<String, Object> zSetOperations = redisTemplate.opsForZSet();
                for (int i =0 ;i<500;i++) {
                    zSetOperations.add("content", i, 1);
                }


                redisTemplate.expire("content", 100L, TimeUnit.SECONDS);
                return null;
            }
        });

        ZSetOperations<String, Object> zSetOperations = redisTemplate.opsForZSet();

        int start = 0;
        int size = 10;
        int contentSize;
        do {

            Set<ZSetOperations.TypedTuple<Object>> content = zSetOperations.rangeWithScores("content", start, start + size);

            for (ZSetOperations.TypedTuple<Object> obj : content) {
                Integer key = (Integer)obj.getValue();
                log.info("key: {}", key);
            }

            start += (size + 1);
            contentSize = content.size();
        } while (contentSize > 0);


    }
}
